<template>
  <div class="step3">
    <h2>
      {{ $t("breach.steps.step3.title") }}
    </h2>
    <div class="action-list">
      <a-button
        icon="plus"
        @click="openAction('new')"
        type="primary"
        class="mb-[10px]"
        :disabled="!ifCanEdit || !role.includes('processor')"
        >{{ $t("user.verification-code.required111566164") }}</a-button
      >
      <a-table
        :columns="actionColumns"
        :dataSource="actionDataSource"
        class="h-full overflow-x-auto"
        :scroll="{ x: 2000 }"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          getCheckboxProps: getCheckboxProps,
        }"
        :pagination="{ current: actionCurrent, total: actionTotal }"
        :rowKey="(record) => record.Id"
        @change="getActionList"
      >
        <template slot="BreachActionUserResponsible" slot-scope="text, record">
          {{
            record.BreachActionUserResponsible === "-"
              ? "-"
              : record.BreachActionUserResponsible.split("@")[0]
          }}
        </template>
        <template slot="BreachActionResult" slot-scope="text, record">
          {{ record.BreachActionResult ? record.BreachActionResult : "N/A" }}
        </template>
        <template slot="BreachActionUpdatetime" slot-scope="text, record">
          {{ record.BreachActionUpdatetime || record.BreachActionCreatetime }}
        </template>
        <span
          slot="BreachActionStatus"
          slot-scope="text, record"
          :style="{
            color: record.BreachActionStatus
              ? actionStatusList.filter(
                  (item) => item.value === record.BreachActionStatus
                )[0]?.color
              : '',
          }"
        >
          {{
            $t(
              record.BreachActionStatus
                ? actionStatusList.filter(
                    (item) => item.value === record.BreachActionStatus
                  )[0].label
                : ""
            )
          }}
        </span>
        <template slot="operate" slot-scope="text, record">
          <!-- 查看 -->
          <a-button
            type="link"
            v-if="
              role.includes('processor') ||
              (role.includes('owner') && record.BreachActionStatus !== 1) ||
              (record.role.actionApprover &&
                (record.BreachActionStatus === 2 ||
                  record.BreachActionStatus === 4)) ||
              currentRole.View ||
              (currentRole.Write && record.BreachActionStatus === 4)
            "
            @click="openAction('view', record.Id)"
            >{{ $t("user.verification-code.required1115661105718") }}</a-button
          >
          <!-- 编辑 -->
          <a-button
            v-if="
              ifCanEdit &&
              ((role.includes('processor') &&
                record.BreachActionStatus !== 4) ||
                (role.includes('owner') &&
                  record.BreachActionUserId === $store.state.user.info.userid &&
                  record.BreachActionStatus === 3) ||
                (currentRole.Write && record.BreachActionStatus !== 4))
            "
            type="link"
            @click="openAction('edit', record.Id)"
            >{{ $t("user.verification-code.required111566147") }}</a-button
          >
          <!-- 删除 -->
          <a-popconfirm
            v-if="
              ifCanEdit &&
              record.BreachActionStatus === 1 &&
              ((role.includes('processor') &&
                record.BreachActionCreateUserId ===
                  $store.state.user.info.userid) ||
                currentRole.Write ||
                !record.BreachActionCreateUserId) &&
              (record.DpiaActionPreset === 2 || breachMode === 2)
            "
            :title="$t('user.verification-code.required111566110577225')"
            :ok-text="$t('user.verification-code.required1166')"
            :cancel-text="$t('user.email.required11')"
            @confirm="() => del(record.Id)"
          >
            <a-button type="link">{{ $t("menu.exception.trigger") }}</a-button>
          </a-popconfirm>
          <!-- 审核 -->
          <a-button
            v-if="
              record.BreachActionStatus === 2 &&
              role.includes('approval') &&
              record.role.actionApprover === 1
            "
            type="link"
            @click="openAction('edit', record.Id)"
            >{{ $t("breach.steps.step3.actionlist.buttons.examine") }}</a-button
          >
        </template>
      </a-table>
    </div>
    <div class="trigger-list">
      <a-button
        class="mb-[10px]"
        icon="plus"
        type="danger"
        :disabled="
          !selectedRowKeys.length ||
          !(role.includes('processor') || role.includes('shareEdit'))
        "
        @click="createRisk"
        >{{ $t("user.verification-code.required1115661105765") }}</a-button
      >
      <h3 class="mb-[10px]">
        {{ $t("breach.steps.step3.triggerlist.title") }}
      </h3>
      <a-table
        :columns="triggerColumns"
        :dataSource="triggerDataSource"
        class="h-full overflow-x-auto"
        :scroll="{ x: 2000 }"
        :pagination="{ current: riskCurrent, total: riskTotal }"
        @change="getTriggerList"
      >
        <template slot="RiskType" slot-scope="text, record">
          {{
            riskType.filter((item) => item.value === record.RiskType)[0]?.label
          }}
        </template>
        <template slot="RiskState" slot-scope="text, record">
          {{
            $t(
              triggerStatusList.filter(
                (item) => item.value === record.RiskState
              )[0]?.label
            )
          }}
        </template>
      </a-table>
    </div>
    <div class="sum">
      {{ $t("breach.steps.step3.sum") }}
      <a-textarea
        rows="4"
        :placeholder="$t('breach.steps.step3.sum.placeholder')"
        :disabled="
          !ifCanEdit ||
          !(role.includes('processor') || role.includes('shareEdit'))
        "
        v-model="EventSummary"
        class="mt-[4px]"
      ></a-textarea>
    </div>
    <div class="buttons mt-[20px]">
      <!-- 上一步 -->
      <a-button
        type="primary"
        icon="left"
        class="mr-[20px]"
        @click="changeStep(1)"
        >{{ $t("breach.steps.step3.buttons.pre") }}</a-button
      >
      <!-- 保存 -->
      <a-button
        type="primary"
        class="mr-[20px]"
        :disabled="
          !ifCanEdit ||
          !(role.includes('processor') || role.includes('shareEdit'))
        "
        @click="save"
        >{{ $t("breach.steps.step2.business.form.buttons.save") }}</a-button
      >
      <!-- 转办 -->
      <a-button
        class="mr-[20px]"
        :disabled="!ifCanEdit || !role.includes('processor')"
        @click="visible = true"
      >
        {{ $t("breach.steps.step2.buttons.turn") }}
      </a-button>
      <!-- 预览报告 -->
      <a-button
        type="primary"
        :disabled="
          !(
            role.includes('processor') ||
            role.includes('shareEdit') ||
            role.includes('shareView')
          )
        "
        class="mr-[20px]"
        @click="changeStep(3)"
      >
        {{ $t("breach.steps.step2.buttons.review") }}
      </a-button>
      <!-- 关闭事件 -->
      <a-button
        :disabled="
          !ifCanEdit ||
          !role.includes('processor') ||
          actionDataSource.filter((item) => item.BreachActionStatus !== 4)
            ?.length !== 0
        "
        :loading="btnLoading"
        @click="closeEvent"
      >
        {{ $t("breach.steps.step1.content.buttons.close") }}
      </a-button>
    </div>
    <step-3-action
      ref="step3Action"
      :role="role"
      :actionList="breachDetail.actionList"
      :breachDetail="breachDetail"
      @getActionList="getActionList"
    />
    <create-risk ref="createRisk" @succeed="() => {}" @getList="init" />
    <a-modal
      v-model="visible"
      :closable="false"
      :title="$t('breach.steps.step2.turn.title')"
    >
      <a-form :form="modalForm">
        <a-form-item :label="$t('breach.steps.step2.turn.processor')">
          <a-select
            :placeholder="$t('breach.steps.step2.turn.processor.placeholder')"
            :disabled="!ifCanEdit"
            v-decorator="[
              'BreachCommentsProcessorId',
              {
                rules: [
                  {
                    required: true,
                    message: $t('breach.steps.step2.turn.processor'),
                  },
                ],
              },
            ]"
            show-search
            @search="getUsers"
          >
            <a-select-option v-for="item in handlerList" :key="item.value">{{
              $t(item.label)
            }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('breach.steps.step2.business.form.call.remark')"
        >
          <a-textarea
            rows="4"
            :placeholder="$t('breach.steps.step2.turn.remark.placeholder')"
            v-decorator="['BreachCommentsInfo']"
            :disabled="!ifCanEdit || !role.includes('processor')"
          ></a-textarea>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <a-button @click="closeModal">{{
          $t("app.setting.content-width.fluid2222333")
        }}</a-button>
        <a-button type="primary" @click="turnTo">{{
          $t("breach.steps.step2.buttons.turn")
        }}</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import createRisk from "@/views/dataAssessment/dpia/onequestion/components/createRisk.vue";
import step3Action from "./step3Action.vue";
import {
  createReport,
  dataBreachTransfer,
  deleteAction,
  getDataActionList,
  getProcessorList,
  getRiskList,
} from "@/api/dataBreach/form";
import { configurationSelect } from "@/api/configs";
import { createDataBreach } from "@/api/dataBreach/json";
export default {
  name: "step3",
  components: { step3Action, createRisk },
  props: ["breachMode", "breachDetail", "ifCanEdit", "role"],
  data() {
    return {
      actionColumns: [
        {
          title: () => this.$t("user.verification-code.required1115661105711"),
          dataIndex: "BreachActionName",
          key: "BreachActionName",
        },
        {
          title: () => this.$t("user.verification-code.required111566173"),
          dataIndex: "BreachActionInfo",
          key: "BreachActionInfo",
        },
        {
          title: () => this.$t("breach.steps.step3.actionlist.result"),
          dataIndex: "BreachActionResult",
          key: "BreachActionResult",
          scopedSlots: { customRender: "BreachActionResult" },
        },
        {
          title: () => this.$t("user.verification-code.required111566174"),
          key: "BreachActionUserResponsible",
          scopedSlots: { customRender: "BreachActionUserResponsible" },
        },
        {
          title: () => this.$t("breach.steps.step3.table.starttime"),
          dataIndex: "BreachActionStartTime",
          key: "BreachActionStartTime",
        },
        {
          title: () => this.$t("breach.steps.step3.table.targettime"),
          dataIndex: "BreachActionFinishTime",
          key: "BreachActionFinishTime",
        },
        {
          title: () => this.$t("user.verification-code.required1115661101"),
          key: "BreachActionStatus",
          scopedSlots: { customRender: "BreachActionStatus" },
        },
        {
          title: () => this.$t("user.verification-code.required1115661105752"),
          dataIndex: "BreachActionUpdatetime",
          key: "BreachActionUpdatetime",
          scopedSlots: { customRender: "BreachActionUpdatetime" },
        },
        {
          title: () => this.$t("di.menus"),
          key: "operate",
          fixed: "right",
          scopedSlots: { customRender: "operate" },
        },
      ],
      actionDataSource: [],
      actionStatusList: [
        { label: "menu.list.search-list112233", value: 1, color: "#515151" }, // 草稿
        {
          label: "user.verification-code.required1115661455555",
          value: 3, // 进行中
          color: "#d3b63e",
        },
        {
          label: "breach.steps.step3.actionlist.status.pending",
          value: 2, // 待审核
          color: "#ebaf47",
        },
        {
          label: "user.verification-code.required111566146",
          value: 4, // 已完成
          color: "#5bc477",
        },
      ],
      selectedRowKeys: [],
      triggerColumns: [
        {
          title: () => this.$t("user.verification-code.required111566123"),
          dataIndex: "RiskId",
          key: "RiskId",
        },
        {
          title: () => this.$t("user.verification-code.required111566125"),
          dataIndex: "RiskName",
          key: "RiskName",
        },
        {
          title: () => this.$t("user.verification-code.required111566126"),
          dataIndex: "RiskSource",
          key: "RiskSource",
        },
        {
          title: () => this.$t("user.verification-code.required111566161"),
          key: "RiskType",
          scopedSlots: { customRender: "RiskType" },
        },
        {
          title: () => this.$t("user.verification-code.required111566158"),
          dataIndex: "RiskOwnerUserName",
          key: "RiskOwnerUserName",
        },
        {
          title: "DCO",
          dataIndex: "RiskDcoUserName",
          key: "RiskDcoUserName",
        },
        {
          title: () => this.$t("breach.steps.step3.triggerlist.createtime"),
          dataIndex: "RiskCreatetime",
          key: "RiskCreatetime",
        },
        {
          title: () => this.$t("breach.steps.step3.triggerlist.targettime"),
          dataIndex: "RiskDeadline",
          key: "RiskDeadline",
        },
        {
          title: () => this.$t("user.verification-code.required1115661101"),
          key: "RiskState",
          scopedSlots: { customRender: "RiskState" },
        },
      ],
      triggerStatusList: [
        { label: "draft", value: 1 },
        { label: "submitted", value: 2 },
        { label: "inProgress", value: 3 },
        { label: "completed", value: 4 },
        { label: "toBeEdited", value: 5 },
      ],
      triggerDataSource: [],
      selectedRows: [],
      visible: false,
      modalForm: this.$form.createForm(this),
      handlerList: [],
      actionTotal: 0,
      currentRole: {},
      actionCurrent: 1,
      riskCurrent: 1,
      riskTotal: 0,
      riskType: [],
      EventSummary: "",
      btnLoading: false
    };
  },
  watch: {
    breachDetail: {
      handler(newVal, oldVal) {
        if (!oldVal || oldVal.Id !== newVal.Id) {
          this.init();
        }
        this.currentRole = newVal.role;
        this.EventSummary = newVal.EventSummary;
      },
      immediate: true,
      deep: true,
    },
  },
  async mounted() {
    this.getUsers();
    const { data } = await configurationSelect({ state: 9 });
    this.riskType = data;
  },
  methods: {
    init() {
      this.getActionList();
      this.getTriggerList();
    },
    openAction(type, Id) {
      this.$refs.step3Action.open(type, Id, this.breachDetail.Id);
    },
    async getActionList(pagination) {
      this.selectedRowKeys = [];
      if (this.breachDetail.Id) {
        this.actionCurrent = pagination?.current || 1;
        let { data } = await getDataActionList({
          BreachId: this.breachDetail.Id,
          page: pagination?.current || 1,
          pageSize: pagination?.pageSize || 10,
        });
        this.actionDataSource = data.Lists;
        this.actionTotal = data.Total;
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
    },
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.BreachActionStatus === 4 || record.RiskId !== 0,
        },
      };
    },
    async getTriggerList(pagination) {
      this.triggerDataSource = [
        {
          id: "id",
          name: "名称",
          from: "来源",
          type: "保密性",
          owner: "张龙",
          DCO: "张龙",
          createtime: "2023-12-27 00:00:00",
          targettime: "2023-12-27 00:00:00",
          status: 1,
        },
      ];
      let { data } = await getRiskList({
        Id: this.breachDetail.Id,
        page: pagination?.current || 1,
        pageSize: pagination?.pageSize || 10,
      });
      this.triggerDataSource = data.Lists;
      this.riskCurrent = pagination?.current || 1;
      this.riskTotal = data.Total;
    },
    createRisk() {
      this.$refs.createRisk.open(this.selectedRowKeys, this.selectedRows, {
        version: "v2",
        data: {
          breachId: this.breachDetail.Id,
        },
      });
    },
    closeModal() {
      this.visible = false;
      this.modalForm.resetFields();
    },
    async turnTo() {
      this.modalForm.validateFields(async (error, value) => {
        if (!error) {
          // 转办
          let { code } = await dataBreachTransfer({
            Id: this.breachDetail.Id,
            ...value,
            BreachCommentsProcessor: this.handlerList.filter(
              (item) => item.value === value.BreachCommentsProcessorId
            )[0]?.label,
          });
          if (code === 1) {
            this.$message.success(
              this.$t("user.verification-code.required111566110577269")
            );
            this.backList();
          }
        }
      });
    },
    async getUsers() {
      let { data } = await getProcessorList();
      this.handlerList = data;
    },
    async del(Id) {
      let { code } = await deleteAction({ Id });
      if (code === 1) {
        this.getActionList();
        this.$message.success(
          this.$t("user.verification-code.required111566110577133")
        );
      }
    },
    async changeStep(step) {
      if (this.role.includes("processor")) this.save(false);
      this.$emit("changeCurrent", step);
    },
    async save(ifReturn = true) {
      // 保存总结
      let { code } = createDataBreach({
        Id: this.breachDetail.Id,
        EventSummary: this.EventSummary,
      });
      if (code === 1) {
        this.$message.success(
          this.$t("user.verification-code.required111566110577308")
        );
        if (ifReturn) this.backList();
      }
    },
    async closeEvent() {
      this.btnLoading = true
      let { code } = await createDataBreach({
        Id: this.breachDetail.Id,
        EventStatus: 5,
      });
      if (code === 1) {
        // 生成报告
        for (let index = 1; index < 3; index++) {
          createReport({
            Id: this.breachDetail.Id,
            lang: index,
          });
        }
        this.$message.success(
          this.$t("user.verification-code.required111566110577308")
        );
        this.backList();
      }
      this.btnLoading = false
    },
    backList() {
      this.$emit("changeIfFlag", true);
      this.$router.push("/breach/list");
    },
  },
};
</script>

<style lang="less" scoped>
.step3 {
  h3 {
    font-size: 18px;
    font-weight: 300;
  }
  .buttons {
    display: flex;
    justify-content: center;
  }
}
</style>